package config

import (
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"log"
	"template/pkg/global"
)

func InitNacos(data []byte) {
	// 加载远程 nacos 配置到全局 viper 对象中
	ReadFromNacos(data)
	// 监听nacos变更
	ListenNacosConfig(data)
}

func ListenNacosConfig(data []byte) error {
	sc := []constant.ServerConfig{{
		IpAddr: global.ViperObj.GetString("app.ipAddr"),
		Port:   uint64(global.ViperObj.GetInt64("app.port")),
	}}

	cc := constant.ClientConfig{
		NamespaceId:         global.ViperObj.GetString("app.namespaceId"), // 如果需要支持多namespace，我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "nacos/log",
		CacheDir:            "nacos/cache",
		LogLevel:            "debug",
		Username:            "nacos",
		Password:            global.ViperObj.GetString("app.password"),
	}
	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": sc,
		"clientConfig":  cc,
	})
	if err != nil {
		log.Fatalf("listen: %s\n", err)
	}
	err = configClient.ListenConfig(vo.ConfigParam{
		DataId: global.ViperObj.GetString("app.dataId"),
		Group:  global.ViperObj.GetString("app.group"),
		OnChange: func(namespace, group, dataId, data1 string) {
			fmt.Println("配置文件发生了变化...")
			fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data1)
			ReadFromNacos(data)
		},
	})
	return err
}
